package cn.cloudplug.instar_ec.accessional.picture;

import android.content.Context;
import android.support.v7.widget.AppCompatImageView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.cloudplug.instar_ec.R;

/**
 * Created by pc on 2018/1/23.
 */

public class PictureAdapter extends BaseAdapter {

    private final List<File> datas=new ArrayList<>();
    private final int first;
    private LayoutInflater mInflater;
    private PicControlMode picControlMode;

    public boolean isShowDeleteButton() {
        return picControlMode.getMode()==PicControlMode.MODEL_DELETE;
    }

    public PictureAdapter(Context context, PicControlMode picControlMode, List<File> datas, int firstRid) {
        mInflater=LayoutInflater.from(context);
        this.picControlMode=picControlMode;
        this.datas.addAll(datas);
        this.first=firstRid;
    }

    @Override
    public int getCount() {
        return datas.size()+1;
    }

    @Override
    public File getItem(int position) {
        if(position<1)return null;
        return datas.get(position-1);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView==null){
            convertView=mInflater.inflate(R.layout.item_gridview,null);
            viewHolder = new ViewHolder();
            viewHolder.imageView=convertView.findViewById(R.id.iv_preview);
            viewHolder.iv_del = convertView.findViewById(R.id.iv_del);
            convertView.setTag(viewHolder);
        }else{
            viewHolder= (ViewHolder) convertView.getTag();
        }
        if(position==0){
            viewHolder.imageView.setImageResource(first);
            viewHolder.imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
            viewHolder.iv_del.setVisibility(View.GONE);
        }else{
            Glide.with(convertView).load(getItem(position)).apply(new RequestOptions().centerCrop()).into(viewHolder.imageView);
            viewHolder.imageView.setScaleType(ImageView.ScaleType.CENTER);
            if(isShowDeleteButton()){
                viewHolder.iv_del.setVisibility(View.VISIBLE);
            }else{
                viewHolder.iv_del.setVisibility(View.GONE);
            }
        }
        return convertView;
    }
    class ViewHolder{
        AppCompatImageView imageView;
        AppCompatImageView iv_del;
    }
}
